import 'dart:async';
import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_constraintlayout/flutter_constraintlayout.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:waterfall_flow/waterfall_flow.dart';
import 'package:wch/constant/resource_constant.dart';
import 'package:wch/native/net_business.dart';
import 'package:wch/page/user_manager.dart';
import 'package:wch/utils/navigator_utils.dart';
import 'package:wch/utils/toast_utils.dart';
import 'package:wch/widget/alert_view.dart';
import 'package:wch/widget/common_widget.dart';
import 'package:wch/widget/text_widget.dart';

import '../constant/event_bus_global.dart';
import '../model/patient_label_list.dart';
import '../model/patient_list.dart';
import '../utils/color_utils.dart';
import '../utils/log_utils.dart';
import '../utils/text_utils.dart';

class DeleteUserPage extends StatefulWidget {
  const DeleteUserPage({super.key, required this.flagsHeight, required this.patientListEntity});

  final List<double> flagsHeight;
  final PatientListModel patientListEntity;
  @override
  State<DeleteUserPage> createState() => _DeleteUserPageState();
}

class _DeleteUserPageState extends State<DeleteUserPage> {
  List<Widget> allWidgets = [];

  List<bool> checkedList = [];

  OverlayEntry? entry;
  
  @override
  void initState() {
    for (int i = 0; i < widget.patientListEntity.data!.data!.length; i ++) {
      checkedList.add(false);
    }
    allWidgets = _getAllItem();
  }

  List<Widget> _getAllItem() {
    List<Widget> all = [];
    // for (int i = 0; i < widget.patientListEntity.data!.data!.length; i++) {
    //   String name = widget.patientListEntity.data!.data![i].na;
    //   all.add(_getUserItem(i, widget.userNames[i]));
    // }
    // return all;

    for (int i = 0; i < widget.patientListEntity.data!.data!.length; i++) {
      PatientListDataData data = widget.patientListEntity.data!.data![i];
      if (data.deviceId != null && data.deviceId!.isNotEmpty) {
        continue;
      }
      String? name;
      String? mobile;
      String? sex;
      String? date;
      for(int j = 0; j < data.list!.length; j ++) {
        PatientListDataDataList user = data.list![j];
        if (user.name == '姓名') {
          name = user.text;
        } else if (user.name == '性别') {
          sex = user.text;
        } else if (user.name == '手机号') {
          mobile = user.text;
        } else if (user.name == '出生日期') {
          date = user.text;
        }
      }
      if (name != null) {
        all.add(_getUserItem(i, data, name, sex, mobile, date));
      }
    }

    return all;
  }

  String showName(String? name) {
    if (name == null || name.isEmpty) {
      return '';
    }
    if (name.length > 4) {
      return '${name.substring(0, 3)}...';
    } else {
      return name;
    }
  }

  Widget _getUserItem(int index, PatientListDataData data, String? name, String? sex, String? mobile, String? date) {
    List<Widget> widgets = [];
    if (data.shopLabelList != null && data.shopLabelList!.isNotEmpty) {
      widgets = _getDoctorWidget(index, data.shopLabelList!);
    }

    double mobileHeight = mobile == null ? 0 : 15.h;
    double dateHeight = date == null ? 0 : 15.h;

    return GestureDetector(
      onTap: (){
        checkedList[index] = !checkedList[index];
        setState(() {
          allWidgets = _getAllItem();
        });
      },
      child: Container(
        height: 73.h + widget.flagsHeight[index] + mobileHeight + dateHeight,
        alignment: Alignment.center,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(7.5.h)),
            color: checkedList[index] ? Color(0xFFEEF2FF) : Colors.white
        ),
        child: ConstraintLayout(
          children: [
            Image.asset(
              sex == '男' ? patientMaleImg : patientFemaleImg,
              width: 23.w,
              height: 23.w,
            ).applyConstraint(
                left: parent.left.margin(15.w),
                top: parent.top.margin(23.h),
                size: 23.w),
            BoldText(
              showName(name),
              fontSize: 15,
            ).applyConstraint(
                left: rId(0).right.margin(5.w),
                top: rId(0).top,),
            Image.asset(
              sex == '男' ? hospitalMaleIcon : hospitalFemaleIcon,
              width: 10.w,
              height: 10.w,
            ).applyConstraint(
                left: rId(1).right.margin(5.w),
                centerVerticalTo: rId(0),
                size: 10.w),
            F12TitleText('分配设备', color: Color(0xFFF78554)).applyConstraint(
                bottom: parent.bottom.margin(0),
                left: parent.left,
                right: parent.right,
                // height: 26.h),
                height: 0),
            LineWidget(width: (ScreenUtil().screenWidth - 30.w) / 2, height: 0.5)
                .applyConstraint(
                left: parent.left,
                right: parent.right,
                // height: 0.5,
                height: 0,
                bottom: rId(3).top.margin(7.h)),
            F14TitleText(date ?? '', color: F1TextColor).applyConstraint(
                left: rId(1).left,
                right: parent.right,
                width: matchConstraint,
                height: date == null ? 0 : 15.h,
                top: rId(1).bottom.margin(7.h)),
            F14TitleText(mobile ?? '', color: F1TextColor).applyConstraint(
              left: rId(1).left,
              right: parent.right,
              width: matchConstraint,
              height: mobile == null ? 0 : 15.h,
              top: rId(5).bottom,
            ),
            Container(
              child: Stack(
                children: widgets,
              ),
            ).applyConstraint(
                left: rId(1).left,
                right: parent.right.margin(25.w),
                width: matchConstraint,
                top: rId(6).bottom.margin(3.h),
                height: widget.flagsHeight[index]
            ),
            Image.asset(checkedList[index] ?  patientCheckedIcon : patientUncheckedIcon, width: 15.w, height: 15.w,).applyConstraint(
                size: 15.w,
                right: parent.right.margin(10.w),
                top: rId(1).top
            )
          ],
        ),
      ),
    );
  }

  List<Widget> _getDoctorWidget(int index, List<PatientLabelListShopLabelList> labelList) {
    // return Container(
    //   margin: EdgeInsets.symmetric(horizontal: 20.w),
    //   padding: EdgeInsets.all(10.w),
    //   child: ,
    // )
    double width = (ScreenUtil().screenWidth - 30.w) / 2 - 70.w;
    // List<String> flags = [];
    // for (int i = 0; i < labelList.length; i ++) {
    //   flags.add('骨科111');
    // }

    List<Widget> widgets = [Container()];

    widget.flagsHeight[index] = 0;
    double posX = 0;
    for (int i = 0; i < labelList.length; i++) {
      Size size = _getTextSize(labelList[i].name!, (ScreenUtil().screenWidth - 30.w) / 2 - 70.w, 10);
      if (widget.flagsHeight[index] == 0) {
        widget.flagsHeight[index] = size.height + 5;
      }
      posX += size.width + 10;
      if (posX > width) {
        posX = size.width + 10;
        widget.flagsHeight[index] += size.height + 10;
      }

      widgets.add(Positioned(
        left: posX - size.width - 10,
        top: widget.flagsHeight[index] - size.height - 5,
        width: size.width + 10,
        height: size.height + 5,
        child: Container(
          alignment: Alignment.center,
          decoration: BoxDecoration(
              color: ColorUtils.getColorFromHex(labelList[i].colour!).withOpacity(0.2),
              borderRadius: BorderRadius.all(Radius.circular(5.w))),
          child: F10TitleText(
            labelList[i].name!,
            color: ColorUtils.getColorFromHex(labelList[i].colour!),
          ),
        ),
      ));

      posX += 5;
    }

    if (widgets.length == 1) {
      widget.flagsHeight[index] = 10;
    }

    return widgets;
  }

  Size _getTextSize(String text, double maxWidth, double fontSize) {
    TextStyle style = TextStyle(
      fontSize: fontSize,
    );
    return TextUtils.boundingTextSize(text, style,
        maxWidth: maxWidth);
  }

  @override
  Widget build(BuildContext context) {
    return CommonScaffold(
      title: '删除用户',
      body: Container(
        color: themeBGC,
        margin: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
        child: WaterfallFlow.builder(gridDelegate: SliverWaterfallFlowDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          crossAxisSpacing: 10.0,
          mainAxisSpacing: 10.0,
          lastChildLayoutTypeBuilder: (index) {
            if (index == allWidgets.length) {
              LogUtils.log('index=$index');
              return LastChildLayoutType.foot;
            } else {
              return LastChildLayoutType.none;
            }
          },
        ), itemBuilder: (ctx, id){
          return allWidgets[id];
        }, itemCount: allWidgets.length,),
      ),
      rightBtn: GestureDetector(
        onTap: () {
          List<int> ids = [];
          for(int i = 0; i < checkedList.length; i ++) {
            if (checkedList[i]) {
              PatientListDataData data = widget.patientListEntity.data!.data![i];
              ids.add(int.parse(data.id!));
            }
          }
          if (ids.isEmpty) {
            ToastUtils.showToast(msg: '请选择要删除的患者');
            return;
          }

          entry = OverlayEntry(builder: (ctx){
            return CommonAlert(title: '删除用户', msg: '确定删除用户吗？', callback:(id){
              if (id == 1){
                _deleteUserLogic(ids);
              }
            }, entry: entry!);
          });
          Overlay.of(context).insert(entry!);
        },
        child: Container(
          padding: EdgeInsets.all(15),
          child: F14TitleText(
            '确定',
            color: themeColor,
          ),
        ),
      ),
    );
  }

  void _deleteUserLogic(List<int> ids) {
    NetBusiness().delPatient(ids).then((value) {
      if (value) {
        ToastUtils.showToast(msg: '删除患者成功');
        Timer.periodic(const Duration(seconds: 1), (timer) {
          timer.cancel();
          globalEventBus.fire(EventBufRefreshModel());
          NavigatorUtil.pop(context);
        });
      }
    });
  }
}
